<template>
  <div class="main-content">
    <el-card style="width: 30%; margin: 30px auto">
      <div class="update">
        <el-button type="primary" @click="dialogVisable = true"
          >修改密码</el-button
        >
        <el-button type="warning" @click="dialogMoneyVisable = true"
          >充值</el-button
        >
      </div>
      <el-form label-width="80px">
        <!-- 头像 -->
        <div class="avatar">
          <img :src="userData.avatar" style="width: 120px;height: 120px;border-radius: 50%;">
        </div>
        <!-- 用户信息 -->
        <el-form-item label="用户名">
          <el-input
            v-model="userData.userName"
            placeholder="用户名"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="userData.realName"
            placeholder="姓名"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input
            v-model="userData.phone"
            placeholder="电话"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="userData.mail"
            placeholder="邮箱"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="余额">
          <el-input
            v-model="userData.money"
            placeholder="余额"
            disabled
          ></el-input>
        </el-form-item>
        <div class="save">
          <el-button type="primary" @click="updateUserInfo"
            >修改个人信息</el-button
          >
        </div>
      </el-form>
    </el-card>
    <!-- 修改密码界面 -->
    <el-dialog
      title="修改密码"
      v-model="dialogVisable"
      width="30%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        label-width="80px"
        style="padding-right: 20px"
        :model="editForm"
        ref="editFormRef"
        :rules="rules"
      >
        <el-form-item label="原始密码" show-password>
          <el-input
            v-model="userData.password"
            disabled
            placeholder="原始密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input
            v-model="editForm.newPass"
            show-password
            placeholder="新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass">
          <el-input
            v-model="editForm.confirmPass"
            show-password
            placeholder="确认密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPass">取 消</el-button>
        <el-button @click="updatePassword" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 余额充值界面 -->
    <el-dialog
      title="余额充值"
      v-model="dialogMoneyVisable"
      width="30%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form :model="editMoneyForm" label-width="80px" style="padding-right: 20px" ref="editMoneyFormRef" >
        <el-form-item label="充值金额">
          <el-input
            v-model.number="editMoneyForm.money"
            placeholder="请输入充值的金额"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancleCharge">取消</el-button>
          <el-button type="primary" @click="charge">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改用户信息界面 -->
    <el-dialog
      title="修改个人信息"
      v-model="dialogFormVisable"
      width="30%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        label-width="80px"
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="userRules"
      >
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/files/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editUserForm.avatar" :src="editUserForm.avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="editUserForm.realName"
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editUserForm.phone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="editUserForm.mail" placeholder="邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetUser">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="person">
import { ref, reactive, onBeforeMount } from "vue";
import { computed } from "vue";
import { ElMessage } from "element-plus";
import { reqUserUpdate, updateUserPassword, reqCharge } from "@/api/user";
import useUserStore from "@/stores/modules/user";

let userStore = useUserStore();

let userData = computed(() => userStore.user);
// 获取修改密码表单实例
let editFormRef = ref<any>();
// 获取余额充值表单实例
let editMoneyFormRef = ref<any>()
// 获取修改用户信息表单实例
let editUserFormRef = ref<any>();
// 修改密码表单
let editForm = reactive({
  newPass: "",
  confirmPass: "",
});
// 修改用户信息的表单
let editUserForm = reactive({
  avatar: "",
  realName: "",
  phone: "",
  mail: "",
});
// 充值的金额
let editMoneyForm = reactive({
  money: null
});
// 控制修改密码界面的显示与隐藏
let dialogVisable = ref(false);
// 控制充值界面的显示与隐藏
let dialogMoneyVisable = ref(false);
// 控制修改用户信息界面的显示与隐藏
let dialogFormVisable = ref(false);

// 头像上传前的回调
const beforeAvatarUpload = (rawFile: any) => {
  // 图片的格式是不是jpeg
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("头像图片必须是JPG格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    // 图片的大小是不是在2mb之下
    ElMessage.error("头像大小不能超过2MB!");
    return false;
  }
  return true;
};

// 头像上传成功的回调
const handleAvatarSuccess = (res: any, uploadFile: any) => {
  // 获取后端返回的图片
  editUserForm.avatar = res.url;
};

// 点击取消充值按钮的回调
const cancleCharge = () => {
  dialogMoneyVisable.value = false;
  editMoneyForm.money = null
}

// 充值余额
const charge = async () => {
  if (typeof editMoneyForm.money !== "number") {
    ElMessage.error("请输入正确的金额类型");
    editMoneyForm.money = null;
    return;
  }
  if(editMoneyForm.money <= 0){
    ElMessage.error("请输入大于0的整数");
    editMoneyForm.money = null;
    return;
  }
  let result = await reqCharge({
    userName: userStore.user.userName,
    money: editMoneyForm.money,
  });
  if (result.code == 200) {
    ElMessage.success(result.msg);
    editMoneyForm.money = null
    dialogMoneyVisable.value = false;
    getUserInfo();
  } else {
    ElMessage.error(result.msg);
  }
};

// 点击修改用户个人信息按钮的回调
const updateUserInfo = () => {
  dialogFormVisable.value = true;
  Object.assign(editUserForm, {
    avatar: userData.value.avatar,
    realName: userData.value.realName,
    mail: userData.value.mail,
    phone: userData.value.phone,
  });
};

// 点击确定修改用户信息按钮的回调
const save = async () => {
  await editUserFormRef.value.validate();
  let data = Object.assign(editUserForm, {
    userName: userData.value.userName,
  });
  let result = await reqUserUpdate(data);
  if (result.code == 200) {
    dialogFormVisable.value = false;
    getUserInfo();
    ElMessage.success(result.msg);
  } else {
    ElMessage.error(result.msg);
  }
};

// 点击取消修改用户信息按钮的回调
const resetUser = () => {
  dialogFormVisable.value = false;
  editUserFormRef.value.resetFields();
};

// 修改密码
const updatePassword = async () => {
  await editFormRef.value.validate();
  try {
    let result = await updateUserPassword({
      userName: userData.value.userName,
      password: editForm.newPass,
    });
    if (result.code == 200) {
      ElMessage.success("密码修改成功！");
      dialogVisable.value = false;
      editForm.newPass = "";
      editForm.confirmPass = "";
      getUserInfo();
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message,
    });
  }
};

// 点击取消修改密码按钮的回调
const resetPass = () => {
  dialogVisable.value = false;
  editFormRef.value.resetFields();
};


// 获取用户信息
const getUserInfo = async () => {
  await userStore.getUserInfo();
};

// 修改密码校验器
// 新密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else if (!/^(?=.*[a-zA-Z])(?=.*\d).{1,9}$/.test(value)) {
    callback(new Error("密码至少包含字母、数字，1-9位"));
  } else {
    if (editForm.confirmPass !== "") {
      if (!editFormRef.value) return;
      editFormRef.value.validateField("confirmPass", () => null);
    }
    callback();
  }
};
// 确认密码
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== editForm.newPass) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

// 密码校验规则
const rules = {
  newPass: [{ validator: validatePass, trigger: "blur" }],
  confirmPass: [{ validator: validatePass2, trigger: "blur" }],
};

// 用户信息校验器
// 手机号
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
// 邮箱
const validateMail = (rule: any, value: any, callback: any) => {
  if (
    !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
      value
    )
  ) {
    callback(new Error("请输入正确的邮箱地址"));
  } else {
    callback();
  }
};

// 用户信息校验规则
const userRules = {
  phone: [{ validator: validatePhone, trigger: "blur" }],
  mail: [{ validator: validateMail, trigger: "blur" }],
};

onBeforeMount(async () => {
  await getUserInfo();
});
</script>

<style scoped lang="scss">
.main-content {
  width: 100%;
  height: 100vh;
  margin: 5px auto;
  .update {
    text-align: right;
    margin-bottom: 20px;
    .el-button--primary {
      color: #fff;
      background-color: #11a983;
      border-color: #11a983;
    }
  }
  .avatar {
    margin: 0 auto;
    width: 120px;
    height: 120px;
    margin-bottom: 10px;
  }
  .avatar-container {
    margin: 15px;
    text-align: center;
    img {
      width: 120px;
      height: 120px;
      display: block;
      border-radius: 50%;
    }
  }
  .dialog-footer {
    padding: 20px;
    padding-top: 10px;
    text-align: right;
    box-sizing: border-box;
  }
  .save {
    text-align: center;
    margin-bottom: 20px;
    .el-button--primary {
      color: #fff;
      background-color: #11a983;
      border-color: #11a983;
    }
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
